package cn.hj.order.service.impl;




import cn.hj.basic.constant.BaseConstant;
import cn.hj.basic.constant.PayConstant;
import cn.hj.basic.service.impl.BaseServiceImpl;
import cn.hj.basic.util.CodeGenerateUtils;
import cn.hj.basic.util.PageList;
import cn.hj.basic.util.QuartzJobInfo;
import cn.hj.order.domain.AdoptOrder;
import cn.hj.order.domain.OrderAddress;
import cn.hj.order.mapper.AdoptOrderMapper;
import cn.hj.order.mapper.OrderAddressMapper;
import cn.hj.order.query.AdoptOrderQuery;
import cn.hj.order.service.IAdoptOrderService;
import cn.hj.org.domain.Employee;
import cn.hj.org.mapper.EmployeeMapper;
import cn.hj.pay.domain.PayBill;
import cn.hj.pay.mapper.PayBillMapper;
import cn.hj.pay.service.IPayBillService;
import cn.hj.pet.domain.Pet;
import cn.hj.pet.mapper.PetMapper;
import cn.hj.quartz.service.IQuartzService;
import cn.hj.user.domain.Logininfo;
import cn.hj.user.domain.User;
import cn.hj.user.domain.UserAddress;
import cn.hj.user.mapper.UserAddressMapper;
import cn.hj.user.mapper.UserMapper;
import com.alipay.api.domain.BillDingBizOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdoptOrderMapper adoptOrderMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;

   @Autowired
   private IQuartzService quartzService;

    @Override
    @Transactional
    public String submit(Map<String, Object> params, Logininfo currentLogininfo) {
        Long serviceMethod = Long.valueOf(params.get("service_method").toString());
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());// // 0 支付宝 1 微信  2 银联
        Long petId = Long.valueOf(params.get("pet_id").toString());

        Pet pet = petMapper.selectById(petId);
        //1.下架宠物
        pet.setState(0);
        pet.setOffsaletime(new Date());
        //2.绑定宠物领养人
        User user = userMapper.getByLogInfoId(currentLogininfo.getId());
        pet.setUser_id(user.getId());
        petMapper.update(pet);

        //3.生成领养订单   //3.1保存订单  //3.2订单地址
        // alt + shift + m  抽取代码成方法
        AdoptOrder order = initAdoptOrder(pet, user);
        //后面生成支付单要统一的支付标识，这里先生成
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        adoptOrderMapper.insert(order);//返回自增ID

        UserAddress address = userAddressMapper.selectById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, address);
        orderAddressMapper.insert(orderAddress);

        // 生成支付单并支付
        PayBill payBill = initPayBill(payMethod, user, order);
        //@TODO 支付超时定时器
        payBillMapper.insert(payBill);
        //支付超时定时器  掉统一的添加定时任务的接口,传递必要的参数
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        jobInfo.setJobName(BaseConstant.PAY_TIMEOUT_CANCEL_ADOPT + order.getId());//jobName
        Map<String,Object> map = new HashMap<>();
        map.put("type",BaseConstant.PAY_TIMEOUT_CANCEL_ADOPT);
        map.put("orderId",order.getId());
        jobInfo.setParams(map);//参数
        jobInfo.setFireDate(order.getLastPayTime());//执行时间
        quartzService.addJob(jobInfo);

        return payBillService.pay(payBill);
    }

    private PayBill initPayBill(Long payMethod, User user, AdoptOrder order) {
        PayBill payBill = new PayBill();
        payBill.setDigest("[摘要]对"+order.getOrderSn()+"支付订单！");
        payBill.setMoney(order.getPrice());
        payBill.setUnionPaySn(order.getPaySn());
        //不设置状态默认有
        payBill.setLastPayTime(order.getLastPayTime());
        payBill.setPayChannel(payMethod); //0  支付宝 1 微信 2 银联
        payBill.setBusinessType(PayConstant.ADOPT_ORDER );
        payBill.setBusinessKey(order.getId());
        payBill.setUser_id(order.getUser_id());
        payBill.setShop_id(order.getShop_id());
        payBill.setNickName(user.getUsername());
        return payBill;
    }

    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress address) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(address,orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        orderAddress.setCreateTime(new Date());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对"+pet.getName()+"领养订单！");
        order.setState(0);//待支付
        order.setPrice(pet.getSaleprice());//售价
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        //最后支付时间
        order.setLastPayTime(new Date(System.currentTimeMillis() + 15*60*1000));
        return order;
    }

    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, Logininfo currentLogininfo) {
        Employee employee = employeeMapper.getByLogInfoId(currentLogininfo.getId());
        if(employee.getShopId() != null){
            query.setShopId(employee.getShopId());
        }
        return super.selectData(query);
    }

    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, Logininfo currentLogininfo) {
        User user = userMapper.getByLogInfoId(currentLogininfo.getId());
        query.setUserId(user.getId());
        return super.selectData(query);
    }


    @Override
    public void cancelOrderByQuartz(Long orderId) {
        AdoptOrder order = adoptOrderMapper.selectById(orderId);
        if(order.getState() == 0){//待支付
            /**
             * 这里有很多业务坑 应该要主动去查一下
             */
            order.setState(-1);
            //这里要不要去直接上架宠物自己看着办
            adoptOrderMapper.update(order);

            System.out.println("定时任务15分钟后执行取消订单:"+order.getId());
        }
    }

}
